// packageI/anytime_service/my/Demand/Demand.js
const app = getApp();
var qqmapsdk;
var QQMapWX = require('../../../../mymap/qqmap-wx-jssdk.min.js');
import Dialog from "../../../../dist/dialog/dialog";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form:{
      province: "",
      city: "",
      district: "",
      streetName: "",
    },
    isShowStreet:false,
    show:false,
    shifu_list:[],
    selectAddressData: [],

   
    startTime: "00:00",
    endTime: "00:00",
    _startTime:"",
    _endTime:"",

    
    radio: '1',
    show_popup:false,

    demand_id:"",

    locationTitle:"",
    point:{},

    type_time:'1',//时间类型 1-服务时间、2-信息有效期

    service_fee: "",
    title: "",
    content: "",
    address: "",
    realname: "",
    info_indate:"",
    order_id:"",
    category_name:"",
    address:"",
    addressName:"",
    timer:"",
    current_date:"",
    openDateLw:false,
    list:[],

    districtVal: [], //街道数据
    streetShow:false,
    
    pickerValue: [0, 0, 0],
    provinceData: [],
    cityData: [],
    districtData: [],
    show_skill_flag:false,
    member_id:"",
    member_src:"",

    start_at:"",
    finish_at:"",
    apply_status:null,//-11-审核驳回

    type:null,
    reason:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({type:options.type||''})
    if(options.demand_id){
      this.setData({demand_id:options.demand_id});
      this.get_detail();
      qqmapsdk = new QQMapWX({
        key: app.globalData.qqmapkey
      });
    }else{
      this.check_apply();
      this.getCategoryData();
      this.getMyLoaction()
      //加载地址数据初始化
      this._initAddressInfo();
    }
  },
  submit_anew(){
    Dialog.confirm({
      title:"提示",
      selector:'#myDialog',
      message: '是否确定重新发布?',
    })
      .then(() => {
        this.submit();
      })
      .catch(() => {
        // on cancel
      });
  },
  check_apply(){
    app._getNetWork({
      url:app.getNetAddresss('plugin.be-within-call.frontend.role-apply.detail'),
      data:{
        role:1,
      },
      success:resdata=>{
        let {result,data} = resdata.data;
        if(result){
          if(data.apply_status!==1){
            wx.navigateTo({
              url: '/packageJ/anytime_service/my/role_apply_for/promulgator/promulgator?role=1',
            })
          }
        }
      }
    })
  },
  order_handle(){
    wx.navigateTo({
      url:`/packageJ/anytime_service/order/order_detail/index?type=individual&order_id=${this.data.order_id}`
    })
  },
   getMyLoaction(){
    var info = wx.getStorageSync('applyaddresspoint') || wx.getStorageSync('address-point');
    console.log(info,"info===");
    if(info){
      this.setData({
        locationTitle: info.address||info.address_component.recommend,
        point: info.point
      })
    }
  },
  getLoaction(){
    qqmapsdk.reverseGeocoder({
      location:{
        latitude:this.data.point.lat,
        longitude:this.data.point.lng
      }, 
      sig: app.globalData.qqmapsig,
      success:resdata=>{
        this.setData({
          locationTitle:resdata.result.address
        })
      },
      fail:error=>{
        console.log(error,"error");
      }
    })
  },
  submit(){
    let valid_time =this.data.info_indate.replace(/-/gi,'/');
    let _time = this.data.info_indate.split(" ");
    if(_time && _time.length!==0){
      valid_time = _time[0]
    }
    
    console.log(valid_time,"=22222===");
    let json = {
      longitude: this.data.point.lng,
      latitude: this.data.point.lat,
      service_fee: this.data.service_fee,
      title: this.data.title,
      content: this.data.content,
      street: this.data.form.streetName,
      address: this.data.address,
      province: this.data.form.province,
      city: this.data.form.city,
      category_id: this.data.radio,
      district: this.data.form.district,
      province_id: this.data.province_id,
      city_id: this.data.city_id,
      district_id: this.data.district_id,
      street_id: this.data.street_id,
      valid_time: new Date(`${valid_time} 00:00:00`).getTime() / 1000,
      start_at:this.data.start_at||this.format_time('start'),
      finish_at:this.data.finish_at||this.format_time('end')
    };
    if (this.data.member_id) {
      json.shifu_uid = this.data.member_id;
    }
    console.log(json,"json==");

    app._postNetWork({
      url:app.getNetAddresss("plugin.be-within-call.frontend.create-need.publish"),
      data:json,
      success:resdata=>{
        let {result,msg,data}=resdata.data;
        app.tips(msg);
        if(result){
          wx.redirectTo ({
            url: '/packageD/buy/orderPay/orderPay?order_id='+data.order_ids
          })
        }
      }
    })
  },
  
  format_time(type) {
    let current_date = this.data.current_date.replace(/-/gi,'/');
    let time = "";
    let startTime =  this.data.timer.split(" ")[1].split("-")[0];
    let endTime =  this.data.timer.split(" ")[1].split("-")[1];
    console.log(startTime,"startTime",endTime,"endTime");
    if (type == 'start') {
      time = `${current_date} ${startTime}:00`;
    } else {
      time = `${current_date} ${endTime}:00`;
    }
    console.log(time,"time==");
    return new Date(time).getTime() / 1000;
  },
  getCategoryData(){
    app._getNetWork({
      url:app.getNetAddresss("plugin.be-within-call.frontend.index.get-category-list"),
      data:{sort_type: 1},
      success:resdata=>{
        let {result,data,msg} = resdata.data;
        if(result){
          this.setData({list:data})
        }else{
          app.tips(msg);
        }
      }
    })
  },
  onInputField(e) {
    let field = e.currentTarget.dataset.field;
    let value = e.detail;

    this.setData({
      [field]: value
    })
    if(this.data.realname && field=='realname'){
      this.get_shifu();
    }else if(!this.data.realname  && field=='realname'){
      this.setData({
        show_skill_flag:false
      })
    }
  },
  choose_handle(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      realname:item.realname,
      show_skill_flag:false,
      member_id:item.member_id,
      member_src:item.personal_pic,
    })
  },
  get_shifu(){
    app._getNetWork({
      url:app.getNetAddresss("plugin.be-within-call.frontend.public-search.easy-shi-fu"),
      data:{kwd:this.data.realname},
      success:resdata=>{
        let {result,data} = resdata.data;
        if(result){
          this.setData({
            show_skill_flag:true,
            shifu_list:data
          })
        }
      }
    })
  },
  onInput(event) {
    let field = event.currentTarget.dataset.v;
    if(field == 'startTime'){
      this.setData({_startTime:event.detail})
    }else{
      this.setData({_endTime:event.detail})
    }
  },
  get_detail(){
    app._getNetWork({
      url:app.getNetAddresss("plugin.be-within-call.frontend.publish.need-detail"),
      data:{id:this.data.demand_id},
      success:resdata=>{
        let {result,msg,data}=resdata.data;
        if(result){
          let timer = data.start_time_str + '-' + data.finish_time_str;
          let addressName = `${data.province_name} ${data.city_name} ${data.district_name}`;
          
          let _time = data.valid_time.split(" ")[0];
          this.setData({
            start_at: new Date(data.start_at).getTime() / 1000,
            finish_at:new Date(data.finish_at).getTime() / 1000,
            radio:data.has_one_category.id,
            apply_status:data.apply_status,
            title:data.title,
            reason:data.reason,
            content:data.content,
            service_fee:data.service_fee,
            addressName,
            province_id:data.province_id,
            city_id:data.city_id,
            district_id:data.district_id,
            street_id:data.street_id,
            "form.province":data.province_name,
            "form.city":data.city_name,
            "form.district":data.district_name,
            "form.streetName":data.street_name,
            address:data.address, 
            category_name:data.has_one_category.title,
            realname:data.has_one_shifu && data.has_one_shifu.realname ||'',
            timer,
            info_indate:_time,
            "point.lat":data.latitude,
            "point.lng":data.longitude,
            order_id:data.order_id
          })
          this.getLoaction();
        }else{
          app.tips(msg);
        }
      }
    })
  },
  show_category(){
    this.setData({show_popup:true})
  },
  toGeolocation() {
    wx.navigateTo({
      url: "/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=storeApply",
    });
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  onClick(event) {
    const  item = event.currentTarget.dataset.item;
    console.log(item,"item");
    this.setData({
      radio: item.id,
      category_name:item.title
    });
  },
  cancle(e){
    let number = e.currentTarget.dataset.i;
    if(number == 1){
      this.setData({show:false})
    }else{
      this.setData({show_popup:false})

    }
  },
  confirm(e){
    let number = e.currentTarget.dataset.i;
    if(number == 1 &&this.data.type_time == 1){
      if (this.data._startTime == '00:00' || this.data._endTime == '00:00') {
        return app.tips("请选择时间")
      } else if (this.data._startTime.split(":")[0] > this.data._endTime.split(":")[0]) {
        return app.tips('开始时间不能小于结束时间')
      } else if (this.data._startTime.split(":")[0] == this.data._endTime.split(":")[0] && this.data._startTime.split(":")[1] == this.data._endTime.split(":")[1]) {
        return app.tips('开始时间不能等于结束时间')
      }
      let timer = `${this.data.current_date} ${this.data._startTime}-${this.data._endTime}`
      this.setData({start_at:"",finish_at:"",show:false,timer})
    }else if(number == 1 &&this.data.type_time == 2){
      this.setData({show:false})
    }else{
      this.setData({show_popup:false})
    }
  },
   // 日历组件点击事件
   select(e) {
     if(this.data.type_time == 1){
      this.setData({
        current_date:e.detail.work_date
      })
     }else{
      this.setData({
        info_indate:e.detail.work_date,
      })
     }
  },
  show_calender(e){
    this.setData({show:true,type_time:e.currentTarget.dataset.v});
  },

  
  //选择街道
  streetConfirm(e) {
    let strname = e.target.dataset.strname;
    let street_id = e.target.dataset.id;
    this.setData({
      "form.streetName": strname,
      streetShow: false,
      street_id
    });
  },
  //打开地址选择器
  openDateLwtbtn: function () {
    this.setData({
      openDateLw: true,
    });
  },
  streetChoose() {
    this.setData({
      streetShow: true,
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        that._getProvinceData();
      },
      fail: function (res) {
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that.setData({
              districtData:district,
              cityData:city,
              provinceData:province,
            })
            // that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          districtData: _json,
        });
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
      },
    });
  },
  _closeDateLw: function () {
    this.setData({
      openDateLw: false,
    });
  },
  _okAddress: function () {
    let seleData = this.data.selectAddressData;
    this.setData({
      district_id:seleData[2].id,
      city_id:seleData[1].id,
      province_id:seleData[0].id,
      "form.streetName": "",
      districtVal: "",
      addressName: seleData[0].name + " " + seleData[1].name + " " + seleData[2].name,
      "form.province": seleData[0].name,
      "form.city": seleData[1].name,
      "form.district": seleData[2].name,
    });
    this._getStreet(seleData[2].id);
    this._closeDateLw();
  },
  //获取街道
  _getStreet(param) {
    var that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              isShowStreet: true,
            });
          } else {
            that.setData({
              isShowStreet: false,
            });
          }
        } else {
          that.setData({
            isShowStreet: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCategoryData();
    this.getMyLoaction()
    this._initAddressInfo();
  }, 

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})